package com.elitel.frame.base.controller;

import com.elitel.frame.base.component.RedisCacheLicenseTxt;
import com.elitel.frame.base.service.UserInfoService;
import com.elitel.frame.core.util.ComputerNumber;
import com.elitel.frame.main.entity.ext.ExtUserInfo;
import com.elitel.frame.main.entity.vo.JsonResult;
import com.elitel.frame.main.entity.vo.LicenseTxt;
import com.elitel.frame.main.security.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/system/authorization")
// @Lazy(false)
// extends LicenseController
public class AuthorizationManagerController {

  private static final Logger logger =
      LoggerFactory.getLogger(AuthorizationManagerController.class);

  @Autowired private RedisCacheLicenseTxt redisCacheLicenseTxt;
  @Autowired private UserInfoService userInfoService;
  @Autowired private JwtTokenUtil jwtTokenUtil;

  /**
   * <pre>uploadSyfBase(上传授权文件)
   * @author：FanWenquan
   * @date：2017年10月27日 下午6:28:07
   * @param myFile
   * @param request
   * @param response
   * @return</pre>
   */
  @RequestMapping("/uploadSyfBase")
  public @ResponseBody Object uploadSyfBase(
      @RequestParam("myFile") MultipartFile myFile,
      HttpServletRequest request,
      HttpServletResponse response) {
    JsonResult jr = new JsonResult();
    if (myFile != null) {
      String uploadRootPath =
              request.getSession().getServletContext().getRealPath("/WEB-INF/license");

      File uploadRootDir = new File(uploadRootPath);
      // Create directory if it not exists.
      if (!uploadRootDir.exists()) {
        uploadRootDir.mkdirs();
      }
      String lname = myFile.getOriginalFilename();
      // url="/WEB-INF/jasper/"+lname;
      if (lname != null && lname.equals("syf.base.dll")) {
        try {
          byte[] bytes = myFile.getBytes();
          // Create the file on server
          File serverFile = new File(uploadRootDir.getAbsolutePath() + File.separator + lname);

          BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
          stream.write(bytes);
          stream.close();
          jr.setSuccess(true);
          jr.setMsg("授权文件上传成功！");
          redisCacheLicenseTxt.deleteLicenseTxtKey();
        } catch (Exception e) {
          logger.error(e.getMessage(), e);
          jr.setMsg("授权文件上传异常");
          jr.setSuccess(false);
          redisCacheLicenseTxt.deleteLicenseTxtKey();
        }
      } else {
        jr.setMsg("授权文件名称非法请重新上传");
        jr.setSuccess(false);
        redisCacheLicenseTxt.deleteLicenseTxtKey();
      }
    }
    return jr;
  }

  /**
   * <pre>validationSyfBase(校验授权文件是否有效)
   * @author：FanWenquan
   * @date：2017年10月27日 下午6:28:30
   * @param request
   * @param response
   * @return</pre>
   */
  @RequestMapping("/validationSyfBase")
  @ResponseBody
  public Object validationSyfBase(HttpServletRequest request, HttpServletResponse response) {
    LicenseTxt licentxt = redisCacheLicenseTxt.readLicenseTxtFile(request, response);
    String cpuNO = ComputerNumber.getCpuSerialNumber();
    String diskNO = ComputerNumber.getDiskSerialNumber();
    String sn = new StringBuffer(ComputerNumber.genSN(cpuNO + diskNO)).insert(4, "-").toString();
    String genCode = ComputerNumber.genSN(licentxt.getLictm0() + licentxt.getLictm1() + sn);
    String licCode = new StringBuffer(genCode).insert(4, "-").toString();
    // 是否过滤
    boolean doFilter = licCode.equals(licentxt.getLiccode());
    return doFilter;
  }

  /**
   * <pre>getComputerSN(获取服务器机器码)
   * @author：FanWenquan
   * @date：2017年10月30日 上午9:27:58
   * @return</pre>
   */
  @RequestMapping("/getComputerSN")
  @ResponseBody
  public Object getComputerSN() {
    JsonResult jr = new JsonResult();
    try {
      String cpuNO = ComputerNumber.getCpuSerialNumber();
      String diskNO = ComputerNumber.getDiskSerialNumber();
      String sn = new StringBuffer(ComputerNumber.genSN(cpuNO + diskNO)).insert(4, "-").toString();
      jr.setData(sn);
      jr.setSuccess(true);
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
      jr.setMsg("获取机器码异常！");
      jr.setSuccess(false);
    }
    return jr;
  }

  /**
   * TODO: 根据用户ID 获取 授权令牌
   *
   * @param authorizationCode
   * @return
   */
  @RequestMapping("/token/{authorizationCode}")
  @ResponseBody
  public Object getToken(@PathVariable String authorizationCode) {
    JsonResult jr = new JsonResult();
    Map<String, Object> result = new HashMap<>();

    if (authorizationCode != null) {
      ExtUserInfo userInfo = userInfoService.selectByAuthorizationCode(authorizationCode);
      if (userInfo != null) {
        String token =
            jwtTokenUtil.generateToken(
                User.withUsername(userInfo.getAuthorizationCode())
                    .password(userInfo.getPassword())
                    .authorities(userInfo.getRole())
                    .build());
        result.put("token", jwtTokenUtil.getType() + token);
        result.put("expires_in", jwtTokenUtil.getExpirationS());
        jr.setSuccess(true);
        jr.setData(result);
        return jr;
      }
    }
    jr.setMsg("invalid userid");
    jr.setSuccess(true);
    return jr;
  }
}
